/***************************************************
 ** @Desc : This file for 代付查询
 ** @Time : 2019.04.11 10:26 
 ** @Author : Joker
 ** @File : pay_query
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019.04.11 10:26
 ** @Software: GoLand
****************************************************/
package controllers

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"net/url"
	"recharge/models"
	"recharge/sys"
	"recharge/utils"
	"recharge/utils/interface_config"
	"strings"
)

type PayQuery struct {
	KeepSession
}

// 多通道代付查询
// @router /merchant/pay_query/?:params [get]
func (the *PayQuery) PayQuery() {
	queryId := the.GetString(":params")

	record := payMdl.SelectOneWithdrawRecord(queryId)
	merchant := merchantMdl.SelectOneMerchantByNo(record.MerchantNo)

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	//只查询处理中的订单
	if strings.Compare(utils.I, record.Status) == 0 {
		// 多通道代付查询
		switch merchant.ChannelType {
		case utils.XF:
			//先锋
			result, err := xfPayQuery(record, merchant.SecretKey)
			if err != nil {
				msg = err.Error()
			} else {

				resp := models.XFPayResponseBody{}
				err = json.Unmarshal(result, &resp)
				if err != nil {
					sys.LogError("response data format is error:", err)
					msg = "先锋代付查询响应数据格式错误"
				} else {

					if strings.Compare("00000", resp.ResCode) != 0 {
						msg = "先锋代付查询错误：" + resp.ResMessage
						record.Remark = resp.ResMessage
						if strings.Compare("10009", resp.ResCode) == 0 {
							record.Status = utils.F
							userMdl.SelectOneUserDeductionForFail(record.UserId, record.WhAmount, record)

							//若是对接订单,发送异步通知
							if strings.Compare(utils.A, record.RecordClass) == 0 {
								go func() {
									apiNotice.ApiPayAsyNotice(record)
								}()
							}
						} else {
							payMdl.UpdateWithdrawRecord(record)
						}
					} else {

						toFen, _ := globalMethod.MoneyYuanToFen(record.WhAmount)
						if strings.Compare(toFen, resp.Amount) != 0 {
							msg = "先锋代付查询金额不匹配"
						} else {

							record.EditTime = globalMethod.GetNowTime()
							record.Status = resp.Status
							record.Remark = resp.ResMessage

							if strings.Compare(utils.S, resp.Status) == 0 {
								WhAmount, _ := globalMethod.MoneyYuanToFen(record.WhAmount)
								//比较金额
								if strings.Compare(WhAmount, resp.Amount) == 0 {
									// 减款
									flag = userMdl.SelectOneUserDeductionForSuccess(record.UserId, record.WhAmount, record)
									if flag > 0 {
										//若是对接订单,发送异步通知
										if strings.Compare(utils.A, record.RecordClass) == 0 {
											go func() {
												apiNotice.ApiPayAsyNotice(record)
											}()
										}
										sys.LogInfo("代付用户:", record.WhOrderId, "减款成功")
									} else {
										sys.LogInfo("代付用户:", record.WhOrderId, "减款失败")
									}

									//发送提现通知
									//info, _ := userMdl.SelectOneUserById(record.UserId)
									//sms.SendSmsForPay(utils.MOBILE, info.UserName)
								}
							} else if strings.Compare(utils.F, resp.Status) == 0 {
								//若是对接订单,发送异步通知
								if strings.Compare(utils.A, record.RecordClass) == 0 {
									go func() {
										apiNotice.ApiPayAsyNotice(record)
									}()
								}
								userMdl.SelectOneUserDeductionForFail(record.UserId, record.WhAmount, record)
							}
						}
					}
				}
			}
		}
	} else {
		msg = "只查询处理中的订单！"
	}

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

// 先锋代付查询
func xfPayQuery(record models.WithdrawRecord, key string, ) ([]byte, error) {
	// 请求参数
	reqParams := url.Values{}
	reqParams.Add("service", "REQ_WITHDRAW_QUERY_BY_ID")
	reqParams.Add("secId", interface_config.SECID)
	reqParams.Add("version", interface_config.VERSION)
	reqParams.Add("reqSn", globalMethod.GetNowTimeV2()+globalMethod.RandomString(12))
	reqParams.Add("merchantId", record.MerchantNo)
	reqParams.Add("merchantNo", record.WhOrderId)

	// 生成签名
	params := reqParams.Encode()
	signBytes, err := merchantImpl.XFGenerateSign(params, key)
	if err != nil {
		s := "先锋代付查询生成签名失败"
		sys.LogTrace(s, err)
		return nil, errors.New(s)
	}
	reqParams.Add("sign", string(signBytes))

	// 发送请求
	resp, err := http.PostForm(interface_config.XF_RECHANGE_URL, reqParams)
	if err != nil {
		s := "先锋代付查询请求失败"
		sys.LogTrace(s, err)
		return nil, errors.New(s)
	}

	// 处理响应
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		s := "先锋代付查询响应为空"
		sys.LogTrace(s, err)
		return nil, errors.New(s)
	}
	defer resp.Body.Close()

	bytes, err := AES.AesDecrypt(body, []byte(key))
	if err != nil {
		s := "先锋代付查询响应解密错误"
		sys.LogTrace(s, err)
		return nil, errors.New(s)
	}

	return bytes, err
}
